package com.studynotes.dev.tech.aspect.datasource;

import com.studynotes.dev.tech.annotation.DataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Liu XiaoJun
 * @description: 动态加载多数据源（启动后加载）
 * @date 2025-11-07 16:43:14
 */
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DynamicDataSourceAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.studynotes.dev.tech.annotation.DataSource) " +
            "|| @within(com.studynotes.dev.tech.annotation.DataSource)")
    public void dynamicDataSourcePointCut() {

    }

    @Around("dynamicDataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class<?> targetClass = point.getTarget().getClass();
        Method method = signature.getMethod();

        DataSource targetDataSource = targetClass.getAnnotation(DataSource.class);
        DataSource methodDataSource = method.getAnnotation(DataSource.class);
        if(targetDataSource != null || methodDataSource != null) {
            String dbLinkKey;
            if (methodDataSource != null) {
                dbLinkKey = methodDataSource.value();
            } else {
                dbLinkKey = targetDataSource.value();
            }
            //根据dbLinkKey动态设置数据源
            DynamicDataSource.setDataSource(dbLinkKey);
        }
        try {
            return point.proceed();
        } finally {
            DynamicContextHolder.poll();
            logger.debug("清理数据源！");
        }
    }

}
